#!/bin/bash

# MCP Proxy Server Startup Script
# Bridges stdio MCP clients to HTTP MCP server

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo -e "${CYAN}🔗 Starting MCP Proxy Server${NC}"
echo -e "${CYAN}===============================${NC}"

# Check if proxy config file exists
PROXY_CONFIG_FILE="config/proxy.json"
if [[ ! -f "$PROXY_CONFIG_FILE" ]]; then
    echo -e "${RED}❌ Proxy configuration file not found: $PROXY_CONFIG_FILE${NC}"
    echo -e "${YELLOW}💡 Please ensure config/proxy.json exists${NC}"
    exit 1
fi

# Check if main config file exists for memory settings
SERVER_CONFIG_FILE="config/server.json"
if [[ ! -f "$SERVER_CONFIG_FILE" ]]; then
    echo -e "${YELLOW}⚠️  Server configuration file not found: $SERVER_CONFIG_FILE${NC}"
    echo -e "${YELLOW}💡 Using default memory settings${NC}"
fi

# Extract memory configuration from JSON (if server config exists)
if [[ -f "$SERVER_CONFIG_FILE" ]]; then
    MAX_OLD_SPACE_SIZE=$(node -e "
    try {
      const config = require('./config/server.json');
      console.log(config.server?.memory?.maxOldSpaceSize || 4096);
    } catch (error) {
      console.log(4096);
    }")

    ENABLE_GC=$(node -e "
    try {
      const config = require('./config/server.json');
      console.log(config.server?.memory?.enableGC !== false ? 'true' : 'false');
    } catch (error) {
      console.log('true');
    }")
else
    MAX_OLD_SPACE_SIZE=4096
    ENABLE_GC="true"
fi

# Extract proxy configuration
HTTP_HOST=$(node -e "
try {
  const config = require('./config/proxy.json');
  console.log(config.proxy?.httpTarget?.host || 'localhost');
} catch (error) {
  console.log('localhost');
}")

HTTP_PORT=$(node -e "
try {
  const config = require('./config/proxy.json');
  console.log(config.proxy?.httpTarget?.port || 3000);
} catch (error) {
  console.log(3000);
}")

HTTP_PROTOCOL=$(node -e "
try {
  const config = require('./config/proxy.json');
  console.log(config.proxy?.httpTarget?.protocol || 'http');
} catch (error) {
  console.log('http');
}")

# Allow environment variable overrides
MCP_HTTP_HOST=${MCP_HTTP_HOST:-$HTTP_HOST}
MCP_HTTP_PORT=${MCP_HTTP_PORT:-$HTTP_PORT}

# Build NODE_OPTIONS
NODE_OPTIONS="--max-old-space-size=${MAX_OLD_SPACE_SIZE}"
if [[ "$ENABLE_GC" == "true" ]]; then
    NODE_OPTIONS="$NODE_OPTIONS --expose-gc"
fi

# Display configuration
echo -e "${GREEN}📋 Proxy Configuration:${NC}"
echo -e "   🎯 Target Server: ${HTTP_PROTOCOL}://${MCP_HTTP_HOST}:${MCP_HTTP_PORT}"
echo -e "   💾 Max Memory: ${MAX_OLD_SPACE_SIZE}MB"
echo -e "   🗑️  GC Enabled: ${ENABLE_GC}"
echo -e "   🔧 NODE_OPTIONS: ${NODE_OPTIONS}"
echo ""

# Check if HTTP server is running
echo -e "${BLUE}🔍 Checking HTTP MCP Server availability...${NC}"
HTTP_URL="${HTTP_PROTOCOL}://${MCP_HTTP_HOST}:${MCP_HTTP_PORT}/health"
if command -v curl >/dev/null 2>&1; then
    if curl -f -s "$HTTP_URL" >/dev/null 2>&1; then
        echo -e "${GREEN}✅ HTTP MCP Server is running and accessible${NC}"
    else
        echo -e "${YELLOW}⚠️  Warning: HTTP MCP Server may not be running at ${HTTP_URL}${NC}"
        echo -e "${YELLOW}💡 Make sure to start it with: npm run start:http${NC}"
        echo ""
        read -p "Continue anyway? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo -e "${RED}❌ Aborted by user${NC}"
            exit 1
        fi
    fi
elif command -v wget >/dev/null 2>&1; then
    if wget -q --spider "$HTTP_URL" 2>/dev/null; then
        echo -e "${GREEN}✅ HTTP MCP Server is running and accessible${NC}"
    else
        echo -e "${YELLOW}⚠️  Warning: HTTP MCP Server may not be running${NC}"
        echo -e "${YELLOW}💡 Make sure to start it with: npm run start:http${NC}"
    fi
else
    echo -e "${YELLOW}⚠️  Cannot check HTTP server status (curl/wget not found)${NC}"
    echo -e "${YELLOW}💡 Make sure HTTP MCP Server is running: npm run start:http${NC}"
fi

echo ""

# Check if build is needed
if [[ ! -d "dist" ]] || [[ "src" -nt "dist" ]]; then
    echo -e "${YELLOW}🔨 Building TypeScript...${NC}"
    npm run build
    echo -e "${GREEN}✅ Build completed${NC}"
    echo ""
fi

# Export environment variables and start proxy
echo -e "${BLUE}🚀 Starting MCP Proxy Server...${NC}"
echo -e "${CYAN}📡 Proxy: stdio ↔ ${HTTP_PROTOCOL}://${MCP_HTTP_HOST}:${MCP_HTTP_PORT}${NC}"
echo -e "${CYAN}💬 Waiting for stdio MCP client connection...${NC}"
echo ""

export NODE_OPTIONS="$NODE_OPTIONS"
export MCP_HTTP_HOST="$MCP_HTTP_HOST"
export MCP_HTTP_PORT="$MCP_HTTP_PORT"

# Start the proxy server
exec node dist/mcp-proxy.js "$@"